var requestHandler = {
  title: '加载中',
  toast: false,
  url: '',
  data: {},
  method: '',
  success: function(res) {},
  fail: function() {},
  complete: function() {}
}

function request(requestHandler) {
  var data = requestHandler.data;
  var url = (requestHandler.url.startsWith('http') ? (requestHandler.url + "&") : (getApp().globalData.HTTP + requestHandler.url + "?")) + 'token=' + getApp().globalData.token;
  var method = requestHandler.method;
  if (requestHandler.toast) {
    wx.showLoading({
      title: requestHandler.title ? requestHandler.title : '加载中',
    })
  }
  wx.request({
    url: url,
    data: data,
    method: method,
    success: function(res) {
      if (res.statusCode == 200) {
        requestHandler.success(res)
      } else {
        if (res.statusCode == 429) {
          wx.showToast({
            title: '请求过于频繁,休息一下.',
            icon: 'none'
          })
        } else {
          if (requestHandler.toast) {
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
          }
        }
      }
    },
    fail: function() {
      if (requestHandler.toast) {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        })
        setTimeout(function() {
          wx.hideLoading()
        }, 2000)
      }
      requestHandler.fail();
    },
    complete: function() {
      requestHandler.complete();
    }
  })
}

module.exports = {
  request: request
}